import os
import re
import sys
import galscript

S_DISCARD = ["■イベントの挿入： コモン501：", "■イベントの挿入： コモン502", "■変数操作: Sys0:顔ｸﾞﾗﾌｨｯｸ番号 = 1 + 0"]
S_VOICE = "■変数操作: V5-11[ボイスログ] = "
S_TEXT = "■文字列操作：S11[ログ] = "
S_PICTURE = "■ﾋﾟｸﾁｬ表示："
S_WAIT = "■ウェイト："
S_SOUND = "■サウンド："
S_SOUND_SE = "■サウンド：SE"
S_COMMAND = "■イベントの挿入： コモン"
S_CLEAR_PICTURE = "■ﾋﾟｸﾁｬ消去："
S_TINT = "■色調変更：(フラッシュ) "

class WolfScript(galscript.ScriptLine):
    def __init__(self, index, text, processor):
        super().__init__(index, text, processor)

    def process_comment(self):
        """
        处理特殊注释行
        返回: 符合要求的XML字符串 或 None
        """
        if self.is_prefix("▼"):
            # 去掉开头的▼符号并保留后续内容
            processed_content = self.text[1:].strip()
            if len(processed_content) == 0:
                self.is_discard = True
            else:
                self.save("Comment", processed_content)
            return True
        return False

    def process_wait(self):
        if self.is_prefix(S_WAIT):
            frame = self.find_int(r"■ウェイト：(\d+) フレーム")
            self.save("Wait", frame)
            return True
        return False


    def process_command(self):
        if self.is_prefix(S_COMMAND):
            command_id = self.find_int(r"コモン(\d+)：")
            command_func = self.find_str(r"\[\s([^/]+?)\s\]")

            # 跳过不需要的Command
            if command_id in [501, 502, 504]:
                return self.discard()
            # 定义ID到名称的映射字典
            COMMAND_MAPPING = {
                222: "ClearPicture",
            }
            # 使用字典查找优化逻辑
            if command_id in COMMAND_MAPPING:
                return self.set_command_xml(COMMAND_MAPPING[command_id])

            self.add_attr("ID", command_id)
            self.save("Event", command_func)
            return True
        return False


    def process_text(self):
        """
        处理特殊文本行
        格式：■文字列操作：S11[ログ] = "文本内容"
        返回: XML格式字符串 或 None
        """
        # 检查固定前缀
        if not self.is_prefix(S_TEXT): return False

        # 提取引号中的内容
        quoted_content = self.text[len(S_TEXT):].strip()
        if not (quoted_content.startswith('"') and quoted_content.endswith('"')):
            return False

        # 去除首尾引号并处理特殊字符
        processed_content = quoted_content[1:-1]  # 去掉引号
        processed_content = re.sub(r"\\font\[\d+\]", '', processed_content)  # 移除所有\font[数字]标记
        processed_content = self.replace_all_text(processed_content) # 处理异常符号

        # 处理下一行的音频
        next = self.processor.get(self.index + 1)
        if next and next.is_prefix(S_VOICE):
            voice_content = next.text[len(S_VOICE):].strip()
            voice_id = voice_content.split()[0]
            self.add_attr("Voice", voice_id)
            next.is_discard = True

        self.save("Text", processed_content)
        return True


    def process_picture(self):
        if not self.is_prefix(S_PICTURE): return False
        r = self.extract_picture_data(self.text)

        # 特殊处理，如果Slot=10，在这个游戏中，代表的是背景
        # 以上这条把Slot=10改为了徐佳莹


        slot = r['PictureID']
        # 依次加入属性
        self.attr = f"Slot='{slot}' "
        self.add_not_default(r, "Anchor", "左上")
        self.add_not_default(r, "Frame", 0)
        self.add_not_default(r, "Delay", 0)
        self.add_not_default(r, "Pattern", 1)
        self.add_not_default(r, "Blend", '通常')
        self.add_not_default(r, "Alpha", 255)
        self.add_not_default(r, "Rotation", 0)
        self.add_not_default(r, "Scale", 100)
        if r["X"] != 0 or r["Y"] != 0:
            self.attr += f"Pos='{r['X']},{r['Y']}' "
        if r["R"] != 100 or r["G"] != 100 or r["B"] != 100:
            self.attr += f"RGB='{r['R']},{r['G']},{r['B']}'"


        self.save("Picture", r["File"])

        # 如果Slot = 10，那么再次设置背景，这样Clear的时候还能保留。他不知道为什么用Slot10来播放
        if (slot == 10):
          self.add_extra_line(f'<Item Type="Bg">{r["File"]}</Item>')

        return True

    def process_clear_picture(self):
        # ■ﾋﾟｸﾁｬ消去：2 ～ 19  / 0(0)ﾌﾚｰﾑ
        # ■ﾋﾟｸﾁｬ消去：2  / 0(0)ﾌﾚｰﾑ
        if not self.is_prefix(S_CLEAR_PICTURE): return False
        frame, delay = self.find_int2(r"(\d+)\((\d+)\)ﾌﾚｰﾑ")
        picture_id = self.find_int(r"ﾋﾟｸﾁｬ消去：(\d+)")
        picture_to_id = self.find_int(r"～ (\d+)")
        self.add_attr_test("Frame", frame, 0)
        self.add_attr_test("Delay", delay, 0)
        self.save("ClearPicture", f"{picture_id}" if picture_to_id == 0 else f"{picture_id}~{picture_to_id}")
        return True

    def process_tint(self):
        # ■色調変更：(フラッシュ) R200 G200 B200 / 20ﾌﾚｰﾑ
        if not self.is_prefix(S_TINT): return False
        r, g, b = self.find_int3(r"R(\d+) G(\d+) B(\d+)")
        frame = self.find_int(r" (\d+)ﾌﾚｰﾑ")
        self.add_attr("Frame", frame)
        self.save("Tint", f"{r},{g},{b}")
        return True

    def extract_picture_data(self, text):
        """
        从字符串中提取所有数字并命名
        示例输入：■ﾋﾟｸﾁｬ表示：10 [左上]ﾌｧｲﾙ｢Picture/e993.png｣ X:0 Y:0 / 0(0)ﾌﾚｰﾑ  / ﾊﾟﾀｰﾝ 1 / 透 255 / 通常  / 角 0 / 拡 100％ / ｶﾗｰ R[100] G[100] B[100]
        """
        # 定义所有可能的数字字段及其匹配模式
        patterns = {
            "PictureID": r"表示：(\d+)",
            "Anchor": r"\[(\w+)\]ﾌｧｲﾙ",
            "File": r"ﾌｧｲﾙ｢(.+?)｣",
            "X": r"X:(-?\d+)",
            "Y": r"Y:(-?\d+)",
            "Frame": r"(\d+)\((\d+)\)ﾌﾚｰﾑ",
            "Pattern": r"ﾊﾟﾀｰﾝ (\d+)",
            "Blend": r"/\s*([^/]+?)\s*/ 角",
            "Alpha": r"透 (\d+)",
            "Rotation": r"角 (\d+)",
            "Scale": r"拡 (\d+)％",
            "R": r"R\[(\d+)\]",
            "G": r"G\[(\d+)\]",
            "B": r"B\[(\d+)\]"
        }

        result = {}
        for name, pattern in patterns.items():
            match = re.search(pattern, text)
            if match:
                if name == "Frame":
                    a, b = map(int, match.groups())
                    result["Frame"] = a
                    result["Delay"] = b
                elif name == "Anchor" or name == "File" or name == "Blend":
                    result[name] = str(match.group(1))
                else:
                    result[name] = int(match.group(1))
            else:
                result[name] = "Undefined"

        return result

    def process_sound(self):
        # 先处理关闭的项目
        if self.is_prefix(S_SOUND):
            if self.has_text("BGS 停止"):
                return self.set_command_xml("StopBGS")
            if self.has_text("BGM 停止"):
                return self.set_command_xml("StopBGM")
            if self.has_text("SE 停止"):
                # 它这其实有Channel的，以后再处理
                return self.set_command_xml("StopSE")

        # 先处理SE，这东西和其它项目不一样。
        if self.is_prefix(S_SOUND_SE):
          # ■サウンド：SE ﾌｧｲﾙ[SE/Microwave_O.mp3] 音 30％ 周 100％ (0 ﾁｬﾝﾈﾙ) 再生  /  遅延：0ﾌﾚｰﾑ
          file = self.find_str(r"ﾌｧｲﾙ\[(.+?)\]")
          volume = self.find_int(r"音 (\d+)％")
          frequency = self.find_int(r"周 (\d+)％")
          channel = self.find_int(r"\((\d+) ﾁｬﾝﾈﾙ\)")
          delay = self.find_int(r"遅延：(\d+)ﾌﾚｰﾑ")
          self.add_attr_test("Volume", volume, 100)
          self.add_attr_test("Frequency", frequency, 100)
          self.add_attr_test("Channel", channel, 0)
          self.add_attr_test("Delay", delay, 0)
          self.save("SE", file)
          return True

        if self.is_prefix(S_SOUND):
            frame_pattern = r"処理時間：(\d+)ﾌﾚｰﾑ"
            bgm = self.find_str(r"BGM([^/]+?)再生")
            bgs = self.find_str(r"BGS([^/]+?)再生")
            id = self.find_int(r"BGM(\d+)" if bgm else r"BGS(\d+)")

            if bgm: self.save("BGM", bgm, f'ID="{id}"')
            elif bgs: self.save("BGS", bgs, f'ID="{id}"')
            else: self.save_undefined()
            return True
        return False

    def check_pass(self):
        is_discard = any(self.text.startswith(prefix) for prefix in S_DISCARD)
        if is_discard:
            self.is_discard = True
        return False


    def process(self):
        if self.is_discard: return
        if self.check_pass(): return

        if self.process_text(): return
        if self.process_picture(): return
        if self.process_sound(): return
        if self.process_clear_picture(): return
        if self.process_tint(): return
        if self.process_wait(): return
        if self.process_command(): return
        if self.process_comment(): return

        # 无法识别的项目
        self.save_undefined()


def process_file(input_file):
    processor = galscript.ScriptProcessor(input_file, lambda idx,name,processor: WolfScript(idx,name,processor))
    processor.process()
    processor.save()

    print(f"处理完成！结果已保存到: {processor.output_file}")

if __name__ == "__main__":
    args = galscript.FileManager()  # 使用imodule中的Args类
    args.foreach_file([".txt"], lambda file: process_file(file))